from odoo import http
from odoo.http import request
import json
import logging
from odoo.addons.api_manager.tools.create_records import create_records
_logger = logging.getLogger(__name__)


class SbGetToken(http.Controller):

    @http.route("/v1.0/sb_api/get_token", auth='public', type='http', methods=['post'], csrf=False)
    def get_token(self, **kwargs):
        """获取token"""
        # 00 定义返回数据格式
        _logger.info('开始请求接口访问token')
        data = request.httprequest.get_json()
        result = {
            'json': True,
            'data': {}
        }
        api_result = {
            'code': 0,
            'message': 'success'
        }
        username = data['params'].get('username', False)
        password = data['params'].get('password', False)
        if not username or not password:
            api_result['code'] = -1
            api_result['message'] = u"必填项未设置"
        else:
            # 2 验证数据密码是否正确
            api_user_model = request.env['api.users']
            api_user_obj = api_user_model.sudo().search([('username', '=', username), ('password', '=', password)],
                                                        limit=1)
            # 2.1 处理用户名或密码不正确的情况
            if api_user_obj and api_user_obj.id:
                token = api_user_obj.sudo().get_token()
                api_result['token'] = token
                _logger.info('运营数据报表：获取token成功')
            else:
                api_result['code'] = -1
                api_result['message'] = u"用户名或密码有误"
        result['data'] = api_result
        _logger.info('请求token流程完成')
        result_json = json.dumps(result, ensure_ascii=False)
        create_records(result_json)
        return http.Response(result_json)

